package com.gdssoft.framework.action.system;

/*
 *  捷达世软件（深圳）有限公司 地铁三号线考勤系统 
 *  Copyright (C) 2008-2010 ShenZhen JieDaShi Software Limited Company.
*/
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.util.AppUtil;
import com.gdssoft.core.util.ContextUtil;
import com.gdssoft.core.web.action.BaseAction;
import com.gdssoft.core.web.paging.PagingBean;
import com.gdssoft.framework.model.system.AppRole;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.framework.model.system.Department;
import com.gdssoft.framework.service.system.AppUserService;
import com.gdssoft.framework.service.system.CompanyService;
import com.gdssoft.framework.service.system.DepartmentService;
import com.gdssoft.framework.service.system.SysConfigService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import flexjson.JSONSerializer;

public class DepartmentAction extends BaseAction{

	private Department department;
	//用于引用角色类里面的角色常量
	private AppRole appRloe = new AppRole();
	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}
	
	@Resource
	private DepartmentService departmentService;
	@Resource
	private AppUserService appUserService;
	@Resource
	private CompanyService companyService;
	@Resource
	private SysConfigService sysConfigService;
	/**
	 * 查询所有的部门信息
	 * @param depId
	 * @return
	 */
	public String select(){
		
		String depId=getRequest().getParameter("depId");
		QueryFilter filter=new QueryFilter(getRequest());
		if(StringUtils.isNotEmpty(depId)&&!"0".equals(depId)){
			department=departmentService.get(new Long(depId));
			filter.addFilter("Q_path_S_LFK", department.getPath());
			
		}
		filter.addSorted("path", "asc");
		List<Department> list=departmentService.getAll(filter);
		Type type=new TypeToken<List<Department>>(){}.getType();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':").append(filter.getPagingBean().getTotalItems()).append(",result:");		
		Gson gson=new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		buff.append(gson.toJson(list, type));
		buff.append("}");
		jsonString=buff.toString();		
		
		return SUCCESS;
	}
	
	
	/**
	 * 查询 指定部门下的所有科室列表
	 * @return
	 */
	public String selectDepSub(){
		
		String depId=getRequest().getParameter("depId");
		QueryFilter filter=new QueryFilter(getRequest());
		filter.addFilter("Q_parentId_L_EQ", depId);
		filter.addSorted("path", "asc");
		List<Department> list=departmentService.getAll(filter);
		Type type=new TypeToken<List<Department>>(){}.getType();
		StringBuffer buff = new StringBuffer("{\"success\":\"true\",\"totalCounts\":").append(filter.getPagingBean().getTotalItems()).append(",\"result\":");		
		Gson gson=new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		buff.append(gson.toJson(list, type));
		buff.append("}");
		jsonString=buff.toString();		
		
		return SUCCESS;
	}
	
	public String list(){
		String opt=getRequest().getParameter("opt");
		StringBuffer buff = new StringBuffer();

		if(StringUtils.isNotEmpty(opt)){
			buff.append("[");
		}else{
			buff.append("[{id:'"+0+"',text:'"+AppUtil.getCompanyName()+"',expanded:true,children:[");
		}

		List<Department> listParent;
		listParent=departmentService.findByParentId(new Long(0));//最顶层父节点
		for(Department dep:listParent){
			buff.append("{id:'"+dep.getDepId()+"',text:'"+dep.getDepName()+"',");
		    buff.append(findChild(dep.getDepId()));
		}
		if (!listParent.isEmpty()) {
			buff.deleteCharAt(buff.length() - 1);
	    }
		if(StringUtils.isNotEmpty(opt)){
		   buff.append("]");
		}else{
			buff.append("]}]");
		}
		setJsonString(buff.toString());
		return SUCCESS;
	}
	
	public String listByDepId(){
		String opt=getRequest().getParameter("opt");
		String depId =getRequest().getParameter("depId");
		StringBuffer buff = new StringBuffer();
		
		buff.append("[");
		
		List<Department> listParent = new ArrayList<Department>();
		//listParent=departmentService.findByParentId(new Long(0),depId);//最顶层父节点
		Department dept = departmentService.get(Long.valueOf(depId));//最顶层父节点
		listParent.add(dept);
		for(Department dep:listParent){
			buff.append("{id:'"+dep.getDepId()+"',text:'"+dep.getDepName()+"',");
		    buff.append(findChild(dep.getDepId()));
		}
		if (!listParent.isEmpty()) {
			buff.deleteCharAt(buff.length() - 1);
	    }
		
		buff.append("]");
		
		setJsonString(buff.toString());
		return SUCCESS;
	}
	public String listByDepIds(){
		String opt=getRequest().getParameter("opt");
		String depIds =getRequest().getParameter("depIds");
		String[] depIdsArray=depIds.split(",");
		
		StringBuffer buff = new StringBuffer();
		
		buff.append("[");
		for(int i=0;i<depIdsArray.length;i++){
			List<Department> listParent = new ArrayList<Department>();
			Department dept = departmentService.get(Long.valueOf(depIdsArray[i]));//最顶层父节点
			listParent.add(dept);
			for(Department dep:listParent){
				buff.append("{id:'"+dep.getDepId()+"',text:'"+dep.getDepName()+"',");
			    buff.append(findChild(dep.getDepId()));
			}
			 buff.append(",");
			if (!listParent.isEmpty()) {
				buff.deleteCharAt(buff.length() - 1);
		    }
		}
		
		buff.append("]");
		
		setJsonString(buff.toString());
		return SUCCESS;
	}
	/*
	 * 寻找子根节点*/
	
	public String findChild(Long depId){
		StringBuffer buff1=new StringBuffer("");
		List<Department> list=departmentService.findByParentId(depId);
		if(list.size()==0){
			buff1.append("leaf:true},");
			return buff1.toString(); 
		}else {
			buff1.append("expanded:true,children:[");
			for(Department dep2:list){				
				buff1.append("{id:'"+dep2.getDepId()+"',text:'"+dep2.getDepName()+"',");
				buff1.append(findChild(dep2.getDepId()));
			}
			buff1.deleteCharAt(buff1.length() - 1);
			buff1.append("]},");
			return buff1.toString();
		}
	}
	
	/*
	 * 寻找子根节点,同时根据员工所在部门过滤*/
	
	public String findChildFilter(Long depId,Long pdepId){
		StringBuffer buff1=new StringBuffer("");
		List<Department> list=departmentService.findByParentId(depId);
		if(list.size()==0){
			buff1.append("leaf:true},");
			return buff1.toString(); 
		}else {
			buff1.append("expanded:true,children:[");
			for(Department dep2:list){
				if(dep2.getDepId()==pdepId)
				{
					buff1.append("{id:'"+dep2.getDepId()+"',text:'"+dep2.getDepName()+"',");
					buff1.append(findChild(dep2.getDepId()));
				}
				else
				{
					buff1.append(findChildFilter(dep2.getDepId(),pdepId));					
				}
			}
			buff1.deleteCharAt(buff1.length() - 1);
			buff1.append("]},");
			return buff1.toString();
		}
	}	
	
	public String add(){		
		Long parentId=department.getParentId();
		String depPath="";
		int level=0;
		if(parentId<1){
			parentId=new Long(0);
			depPath="0.";
		}else{
			depPath=departmentService.get(parentId).getPath();
			level=departmentService.get(parentId).getDepLevel();
		}
		if(level<1){
			level=1;			
		}

		department.setDepLevel(level+1);
		try {
			
			departmentService.save(department);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		if(department!=null){
		    depPath+=department.getDepId().toString()+".";
		    department.setPath(depPath);
		    try {
				
				departmentService.save(department);
			} catch (Exception e) {
				
				e.printStackTrace();
			}		
		    setJsonString("{success:true}");
		}else{
			 setJsonString("{success:false}");
		}
		return SUCCESS;
	}
	
	public String remove(){
		PagingBean pb=getInitPagingBean();
		Long depId=Long.parseLong(getRequest().getParameter("depId"));
		Department department=departmentService.get(depId);
		
		//List userList=appUserService.findByDepartment(department.getPath(), pb);
    	/*if(department.getEmployees().size()>0){
    		setJsonString("{success:false,message:'该部门还有人员，请将人员转移后再删除部门!'}");
    		return SUCCESS;
    	}*/
		try {
			
			departmentService.remove(depId);
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	    /*List<Department> list=departmentService.findByParentId(depId);
	    for(Department dep:list){
	    	//List users=appUserService.findByDepartment(dep.getPath(), pb);
	    	if(dep.getEmployees().size()>0){
	    		setJsonString("{success:false,message:'该部门还有人员，请将人员转移后再删除部门!'}");
	    		return SUCCESS;
	    	}
	    	departmentService.remove(dep.getDepId());
	    }*/
	    setJsonString("{success:true}");
		return SUCCESS;
	}
	
	public String detail(){
		Long depId=Long.parseLong(getRequest().getParameter("depId"));
		setDepartment(departmentService.get(depId));
//		Gson gson=new Gson();
		StringBuffer sb = new StringBuffer("{success:true,data:[");
		JSONSerializer serializer=new JSONSerializer();
//		sb.append(gson.toJson(department));
		sb.append(serializer.exclude(new String[] { "class" }).serialize(department));
		sb.append("]}");
		setJsonString(sb.toString());
		return SUCCESS;
	}
	
	public String get(){
		Long depId=Long.parseLong(getRequest().getParameter("depId"));
		Department department =departmentService.get(depId);
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").excludeFieldsWithoutExposeAnnotation()
		.create();
		//将数据转成JSON格式
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(gson.toJson(department));
		sb.append("}");
		setJsonString(sb.toString());
		return SUCCESS;
	}
	
	/**
	 * Combo控件数据填写
	 * 
	 */
	public String combo(){
		QueryFilter filter = new QueryFilter(getRequest());
		filter.getPagingBean().setPageSize(99999);
		StringBuffer sb=new StringBuffer();
		AppUser appUser = ContextUtil.getCurrentUser();
		boolean isAdmin = false;
		for(AppRole role:(appUser.getRoles()).toArray(new AppRole[0]))
		{
			if (role.getRoleId() == -1L)
			{
				isAdmin = true;
				break;
			}
		}
		if (!isAdmin)
		{
			//filter.addFilter("Q_depId_L_EQ", appUser.getEmployee().getDepartment().getDepId().toString());
		}
		List<Department> departmentList=departmentService.getAll(filter);
		sb.append("[");

		for(Department department:departmentList){
			sb.append("['").append(department.getDepId()).append("','").append(department.getDepName()).append("'],");
		}
		if(departmentList.size()>0){
			sb.deleteCharAt(sb.length()-1);
		}
		sb.append("]");
		setJsonString(sb.toString());
		return SUCCESS;
	}	
	
	/*
	 * 寻找子根节点
	 */
	public String findChild(Long depId,Integer level) {
		StringBuffer buff1 = new StringBuffer("");
		List<Department> list = departmentService.findByParentId(depId,level,null);
		if (list.size() == 0) {
			buff1.append("leaf:true},");
			return buff1.toString();
		} else {
			buff1.append("expanded:true,children:[");
			for (Department dep2 : list) {
				buff1.append("{id:'" + dep2.getDepId() + "',text:'"
						+ dep2.getDepName() + "',");
				buff1.append(findChild(dep2.getDepId(), level));
			}
			buff1.deleteCharAt(buff1.length() - 1);
			buff1.append("]},");
			return buff1.toString();
		}
	}

	/**
	 * 获取公司树 
	 * 最顶层父节点1开始，0为未加入组织的公司
	 * @return
	 */
	public String treeByLevel() {
		String levelStr = getRequest().getParameter("depLevel");
		Integer level = levelStr==null?null:Integer.parseInt(levelStr);
		StringBuffer buff = new StringBuffer("[");
		
		Long parentId = -1L;
		AppUser au = ContextUtil.getCurrentUser();
		if(appUserService.hasRole(au, "ROLE_SUPER")){	//super
			parentId = 1L;
		} else {
			parentId = au.getDepId();
		}
		
		Department thisdep =  departmentService.get(parentId);
		if(thisdep != null){
			buff.append("{id:'" + thisdep.getDepId() + "',text:'" + thisdep.getDepName() + "',");
			buff.append(findChild(thisdep.getDepId(),level));
		}else{
			List<Department> listParent = departmentService.findByParentId(parentId,level,null);
			for (Department dep : listParent) {
				buff.append("{id:'" + dep.getDepId() + "',text:'" + dep.getDepName() + "',");
				buff.append(findChild(dep.getDepId(),level));
			}
		}

		if (buff.length() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		setJsonString(buff.toString());
		
		return SUCCESS;
	}

}
